package com.mrd.gtimp.login.action;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mrd.base.Jqgrid;
import com.mrd.constant.MsgConstants;
import com.mrd.constant.RoleType;
import com.mrd.exception.QueryException;
import com.mrd.framework.config.web.json.Result;
import com.mrd.framework.config.web.json.annotation.JField;
import com.mrd.framework.config.web.json.annotation.Json;
import com.mrd.framework.security.config.SecurityConstants;
import com.mrd.framework.ui.filter.Filter;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.framework.utils.HttpUtils;
import com.mrd.gtimp.base.entity.Module;
import com.mrd.gtimp.base.entity.Role;
import com.mrd.gtimp.base.entity.User;
import com.mrd.gtimp.base.service.ModuleBiz;
import com.mrd.gtimp.base.service.RoleBiz;
import com.mrd.gtimp.base.service.UserBiz;
import com.mrd.gtimp.business.entity.Contacter;
import com.mrd.gtimp.business.entity.DeclarationOffer;
import com.mrd.gtimp.business.service.ContacterBiz;
import com.mrd.gtimp.business.service.DeclarationBiz;
import com.mrd.gtimp.business.service.DeclarationOfferBiz;
import com.mrd.gtimpframe.entity.Declaration;
import com.mrd.gtimpframe.entity.RejectRecord;
import com.mrd.gtimpframe.entity.UserService;
import com.mrd.gtimpframe.service.RejectRecordService;
import com.mrd.gtimpframe.service.UserServiceService;
import com.mrd.util.CollectionUtil;
import com.mrd.util.IFilter;
import com.mrd.util.LoginUtil;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

/**
 * <p> application name: sample <p> copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author winaya
 */
@Controller
@RequestMapping("/")
public class IndexAction {

    private static final long serialVersionUID = -5256839802049184528L;
    @Resource
    private ModuleBiz moduleBiz;

    @Resource
    private ContacterBiz contacterBiz;
    @Resource
    private UserBiz userBiz;
    private List<Module> modules;

    private String id;
    @Resource
    private DeclarationBiz declarationBiz;

    @Resource
    private DeclarationOfferBiz declarationOfferBiz;

    private List<DeclarationOffer> declarationOffers = null;

    @Resource
    private UserServiceService userServiceService;
    @Resource
    private RejectRecordService rejectRecordService;

    /**
     * 发货人
     */
    private Contacter shipper;
    @Resource
    private RoleBiz roleBiz;

    @RequestMapping("/index")
    public String index() throws Exception {
        if (LoginUtil.isLogin() && LoginUtil.getLoginUser() == null) {
            User systemUser = userBiz.findByAccount(LoginUtil.getLoginAccount());
            HttpUtils.getSession().setAttribute(SecurityConstants.SESSION_USER_NAME, systemUser);
            HttpUtils.getSession()
                    .setAttribute(SecurityConstants.SESSION_ROLE_NAME, systemUser.getRoles());
            String companyType = systemUser.getCompany().getType();
            // 取得角色
            HttpUtils.getSession()
                    .setAttribute(SecurityConstants.SESSION_ROLE_NAME, StringUtils
                            .isNotEmpty(companyType) && companyType.equalsIgnoreCase("CC")
                            ? RoleType.supplier : RoleType.customer);
            Set<Module> moduleSet = new HashSet<>();
            for (Role role : systemUser.getRoles()) {
                moduleSet.addAll(role.getModules());
            }
            systemUser.setModules(new ArrayList<>(moduleSet));
            systemUser.getCompany();

			/*
             * 将登陆用户中的2.0角色转换成3.0角色
			 */
            moduleSet.clear();
            List<Role> v30Roles = roleBiz.v20RolesConvertToV30(systemUser.getRoles());
            for (Role v30Role : v30Roles) {
                moduleSet.addAll(v30Role.getModules());
            }
            systemUser.setModules(new ArrayList<>(moduleSet));
            // 角色转换自本行结束

            HttpUtils.getSession()
                    .setAttribute(SecurityConstants.SESSION_PERMISSION_MODULE_NAME, systemUser
                            .getModules());
            contacterBiz.saveContacter();
        }
        return "/gtimp/index";
    }

    @RequestMapping("/loginUserInfo")
    public String loginUserInfo(Model model) throws Exception {
        // User u = (User) sessionMap.get(SystemConstants.CURRENT_USER);
        User u = LoginUtil.getLoginUser();
        Contacter shipper = new Contacter();
        if (null == u) {
            return "loginUserInfo";
        }
        String name1 = u.getName();
        if (null != u.getDepts() && null != u.getDepts().get(0).getCompany()) {
            String companyName1 = u.getDepts().get(0).getCompany().getName();
            String address1 = u.getDepts().get(0).getCompany().getAddress();
            String fax1 = u.getDepts().get(0).getCompany().getFax();
            String phone1 = u.getMobile();
            String sql = "from com.mrd.gtimp.business.entity.Contacter where name='" + name1
                    + "' and company='" + companyName1 + "' and address='" + address1
                    + "' and fax='" + fax1 + "' and phone='" + phone1 + "'";
            List<Contacter> contacter = contacterBiz.findEntityByHql(sql, 0, 10, null);
            if (contacter.size() > 0) {
                shipper.setId(contacter.get(0).getId());
            }
            shipper.setName(name1);
            shipper.setCompany(companyName1);
            shipper.setAddress(address1);
            shipper.setFax(fax1);
            shipper.setPhone(u.getMobile());
            shipper.setEmail(u.getEmail());
        }
        model.addAttribute("shipper", shipper);
        UserService parameters = new UserService();
        parameters.setUserId(u.getId());
        parameters.setStatus("1");
        parameters.setServerType("SMS");
        List<UserService> userServiceList = userServiceService.selectSelective(parameters);
        if (userServiceList != null && userServiceList.size() > 0) {
            model.addAttribute("userService", userServiceList.get(0));
        }
        return "/gtimp/loginUserInfo";
    }

    @RequestMapping("/welcome")
    public String welcome() throws Exception {
        return "/gtimp/webcome";
    }

    /**
     * 首页
     */
    @RequestMapping("/customWelcome")
    public String customWelcome() throws Exception {
        return "/customWelcome";
    }

    /**
     * 注册与登录
     */
    @RequestMapping("/regLogin")
    public String regLogin() {
        return "/gtimp/helpCenter/regLogin";
    }

    /**
     * 密码设置
     */
    @RequestMapping("/resetPass")
    public String resetPass() {
        return "/gtimp/helpCenter/resetPass";
    }

    /**
     * 在线咨询
     */
    @RequestMapping("/onlineAdvice")
    public String onlineAdvice() {
        return "/gtimp/helpCenter/onlineAdvice";
    }

    /**
     * 操作指引
     */
    @RequestMapping("/operationlGuide")
    public String operationlGuide() {
        return "/gtimp/helpCenter/operationlGuide";
    }

    /**
     * 服务协议
     */
    @RequestMapping("/serviceAgreement")
    public String serviceAgreement() {
        return "/gtimp/helpCenter/serviceAgreement";
    }

    /**
     * 微信活动
     */
    @RequestMapping("/weixinActivity")
    public String weixinActivity() {
        return "/helpCenter/cweixinhuodong";
    }

    /**
     * 在线查询
     */
    @RequestMapping("/searching")
    public String searching() {
        return "/searching";
    }

    /**
     * 浏览器支持页面
     */
    @RequestMapping("/browser")
    public String browser() {
        return "/browser";
    }

    @RequestMapping("/index-module")
    @ResponseBody
    @Json({@JField("id"), @JField("name"), @JField("link"), @JField("parent.id"), @JField("order"),
            @JField("isParent")})
    public List<Module> module(@RequestParam(required = false) String id) throws Exception {
        IFilter<Module> moduleFilter = new ModuleFilter(id);
        if (LoginUtil.getLoginUserModules() != null) {
            List<Module> modules = CollectionUtil
                    .list(LoginUtil.getLoginUserModules(), moduleFilter);
            Collections.sort(modules);
            return modules;
        }
        return null;
    }

    @RequestMapping("/index-refresh")
    @ResponseBody
    public String refresh(User user) throws Exception {
        String msg = "";
        String comId = user.getCompany().getId();// 此处为供应商
        // String listCase =
        // "select sval.chn, declaration from com.mrd.gtimp.business.pojo.Declaration declaration,
        // com.mrd.gtimp.base.pojo.SystemValue sval "
        // +
        // "where declaration.state = sval.identifier and (1 = 1 and declaration.supCompany.id =
        // '402881e93c5bf1a8013c5c46da710006' and declaration.state = 'DS01' "
        // +
        // "or declaration.id in (select bf.bizId from com.mrd.gtimp.business.pojo.BizFlow bf where
        // bf.scompany = '402881e93c5bf1a8013c5c46da710006' "
        // +
        // "or bf.tcompany = '402881e93c5bf1a8013c5c46da710006')) and declaration.state = 'DS01'
        // order by declaration.businessId desc";
        String listCase = " select sval.chn, declaration from com.mrd.gtimp.business.pojo.Declaration declaration, com.mrd.gtimp.base.pojo.SystemValue sval "
                + " where declaration.state = sval.identifier and (1 = 1 and declaration.supCompany.id = '"
                + comId + "' and declaration.state = 'DS01' "
                + " or declaration.id in (select bf.bizId from com.mrd.gtimp.business.pojo.BizFlow bf where bf.scompany = '"
                + comId + "' " + " or bf.tcompany = '" + comId
                + "')) and declaration.state = 'DS01' order by declaration.businessId desc";
        List<Object> objList = declarationBiz.findObjectByHql(listCase, 0, 500, null);
        if (objList.size() > 0) {
            String count = String.valueOf(objList.size());
            msg = "{\"state\":0,\"msg\":\"您有" + count + "票单需要进行审核！\"}";
        } else {
            msg = "{\"state\":1,\"msg\":\"您暂时没有单证需要进行审核！\"}";
        }
        return msg;
    }

    @RequestMapping("/index-remindDeclarationDue")
    @ResponseBody
    public String remindDeclarationDue() {
        String msg = "";
        String companyId = LoginUtil.getLoginUser().getCompany().getId();
        // String hql = "from com.mrd.gtimp.business.pojo.DeclarationOffer offer where
        // offer.declaration_company_id='"
        // + companyId + "' and offer.state='OS05'";
        // declarationOffers = declarationOfferBiz.findEntityByHql(hql, 0, 10,
        // null);
        Filter filter = new Filter();
        filter.addRule(new SearchRule("declaration_company_id", SearchRuleOption.eq, companyId));
        filter.addRule(new SearchRule("state", SearchRuleOption.eq, "OS05"));
        List<DeclarationOffer> declarationOffers = null;
        try {
            declarationOffers = declarationOfferBiz.findEntityByFilter(0, 10, filter, null);
            Date priceEndTime = null;
            int days = 0;
            if (declarationOffers.size() > 0) {
                priceEndTime = declarationOffers.get(0).getPrice_end_time();
                long intervalMilli = priceEndTime.getTime() - new Date().getTime();
                days = (int) (intervalMilli / (24 * 60 * 60 * 1000));
                if (days > 15) {
                    msg = "{\"state\":1,\"days\":\"" + days + "\"}";
                } else {
                    msg = "{\"state\":0,\"days\":\"" + days + "\"}";
                }
            }
            return msg;
        } catch (QueryException e) {
            e.printStackTrace();
        }
        return msg;
    }

    /**
     * 计算获得驳回的数量
     */
    @RequestMapping("/index-countReject")
    @ResponseBody
    public Result countReject() {
        if (LoginUtil.isLogin() && LoginUtil.getLoginUser() != null) {
            User user = LoginUtil.getLoginUser();
            Jqgrid jqgrid = new Jqgrid();
            jqgrid.addRule(new SearchRule("STATE", SearchRuleOption.eq, Declaration.DeclarationBusinessState.REJECT_STATE));
            if (!user.getCompany().getName().equals("佛山市佛航展翔物流有限公司") || !user.getType().equals("0")) {
                jqgrid.addRule(new SearchRule("CUSTOMER_COM_ID", SearchRuleOption.eq, user.getCompany().getId()));
                jqgrid.addRule(new SearchRule("T_BIZ_DECLA_RELASTIONSHIP.PARENT", SearchRuleOption.inl, ""));
                jqgrid.addRule(new SearchRule("ACCEPTED_RESULT", SearchRuleOption.ni, "NOT_ACCEPTED"));
            }
            PageHelper.startPage(1, 1);
            Map<String, String> propertyMap = new HashMap<>();
            propertyMap.put("whereCase", jqgrid.getWhereCase());
            List<RejectRecord> rejectRecords = rejectRecordService.selectByWhereCase(propertyMap);
            PageInfo<RejectRecord> pi = new PageInfo<>(rejectRecords);
            return Result.newSuccessInstance(MsgConstants.SAVE_SUECCES, pi.getTotal() + "");
        }
        return Result.newFailInstance(MsgConstants.SAVE_FAIL);
    }

    /**
     * 计算待审核公司的数量
     */
    @RequestMapping("/index-countNewReg")
    @ResponseBody
    public Result countNewReg() {
        if (LoginUtil.isLogin() && LoginUtil.getLoginUser() != null) {
            User user = userBiz.findByAccount(LoginUtil.getLoginAccount());
            String hql = " select count(*) from com.mrd.gtimp.business.entity.RegisteredCompany c"
                    + " where (c.platform_approve_status = ''"
                    + " or c.platform_approve_status is null) and c.reg_time > to_date('20161227','yyyymmdd')";
            String result = "";
            try {
                int count = declarationBiz.findEntityCountByHql(hql, null);
                result = count + "";
            } catch (QueryException e) {
                e.printStackTrace();
            }
            return Result.newSuccessInstance(MsgConstants.SAVE_SUECCES, result);
        }
        return Result.newFailInstance(MsgConstants.SAVE_FAIL);
    }

    /**
     * 计算待审核收发货人记录的数量
     */
    @RequestMapping("/index-countCompanyQpTemp")
    @ResponseBody
    public Result countCompanyQpTemp() {
        if (LoginUtil.isLogin() && LoginUtil.getLoginUser() != null) {
            User user = userBiz.findByAccount(LoginUtil.getLoginAccount());
            String hql = " select count(*) from com.mrd.gtimp.business.entity.CompanyQpTemp c"
                    + " where c.closed='0'";
            String result = "";
            try {
                int count = declarationBiz.findEntityCountByHql(hql, null);
                result = count + "";
            } catch (QueryException e) {
                e.printStackTrace();
            }
            return Result.newSuccessInstance(MsgConstants.SAVE_SUECCES, result);
        }
        return Result.newFailInstance(MsgConstants.SAVE_FAIL);
    }

    /**
     * 计算待审核付款记录的数量
     */
    @RequestMapping("/index-countOfflinePay")
    @ResponseBody
    public Result countOfflinePay() {
        if (LoginUtil.isLogin() && LoginUtil.getLoginUser() != null) {
            User user = userBiz.findByAccount(LoginUtil.getLoginAccount());
            String hql = " select count(*) from com.mrd.gtimp.business.entity.FundAjustment c"
                    + " where c.state='INIT' and c.fundPayType<>'ONLINE' and c.regDate > to_date('20170110','yyyymmdd')";
            String result = "";
            try {
                int count = declarationBiz.findEntityCountByHql(hql, null);
                result = count + "";
            } catch (QueryException e) {
                e.printStackTrace();
            }
            return Result.newSuccessInstance(MsgConstants.SAVE_SUECCES, result);
        }
        return Result.newFailInstance(MsgConstants.SAVE_FAIL);
    }

    @RequestMapping("/index-companyType")
    public String companyType(User user) {
        String msg = "";
        String companyType = user.getCompany().getType();
        msg = "{\"type\": \"" + companyType + "\"}";
        return msg;
    }

    /**
     * 跳转QP上传
     */
    @RequestMapping("/qp")
    public String qp() {
        return "/qp";
    }

    public List<Module> getModules() {
        return modules;
    }

    public void setModules(List<Module> modules) {
        this.modules = modules;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    private class ModuleFilter implements IFilter<Module> {
        private final String pid;

        public ModuleFilter(String pid) {
            if (pid == null) {
                this.pid = null;
            } else {
                this.pid = pid.trim();
            }
        }

        public boolean filter(Module e) {
            if (StringUtils.isBlank(pid)) {
                return e.getParent() == null || StringUtils.isBlank(e.getParent().getId());
            } else {
                return e.getParent() != null && pid.equals(e.getParent().getId());
            }
        }

    }

    public Contacter getShipper() {
        return shipper;
    }

    public void setShipper(Contacter shipper) {
        this.shipper = shipper;
    }

    /**
     * 计算申请驳回而未处理的报关单数量
     */
    @RequestMapping("/index-applyRejectCount")
    @ResponseBody
    public Result applyRejectCount() {
        if (LoginUtil.isLogin() && LoginUtil.getLoginUser() != null) {
            User user = LoginUtil.getLoginUser();
            Jqgrid jqgrid = new Jqgrid();
            jqgrid.addRule(new SearchRule("ACCEPTED_RESULT", SearchRuleOption.eq, "INITIATED"));//发起驳回
            jqgrid.addRule(new SearchRule("T_BIZ_BASE_BUSINESS.SUP_ID", SearchRuleOption.eq, user.getCompany().getId()));
//            保持和已受理页面一样的查询状态
            jqgrid.addRule(new SearchRule("T_BIZ_DECLARATION.STATE", SearchRuleOption.ni, "DS00,DS01,DS03,DS030"));
            PageHelper.startPage(1, 1);
            Map<String, String> propertyMap = new HashMap<>();
            propertyMap.put("whereCase", jqgrid.getWhereCase());
            List<RejectRecord> rejectRecords = rejectRecordService.selectByWhereCase(propertyMap);
            PageInfo<RejectRecord> pi = new PageInfo<>(rejectRecords);
            return Result.newSuccessInstance(MsgConstants.SAVE_SUECCES, pi.getTotal() + "");
        }
        return Result.newFailInstance(MsgConstants.SAVE_FAIL);
    }
}
